#!/bin/bash

# Desc: convert gfwlist.txt into privoxy.action
# Usage: bash gfwlist2privoxy <socks5_addr:socks5_port>
# Dependency: base64, curl(https support), perl5 v5.10.0+

# check dependency
command -v curl &>/dev/null || { echo "curl is not installed in this system" 1>&2; exit 1; }
command -v perl &>/dev/null || { echo "perl is not installed in this system" 1>&2; exit 1; }
command -v base64 &>/dev/null || { echo "base64 is not installed in this system" 1>&2; exit 1; }

# parse command line
gfwlist_action='gfwlist.action'
test $# -lt 1 && { echo "Usage: bash gfwlist2privoxy <socks5_addr:socks5_port>"; exit 1; }
perl -e 'exit 1 if $ARGV[0] !~ /^\d+\.\d+\.\d+\.\d+:\d+$/' "$1" || { echo "Invalid address format: '$1'" 1>&2; exit 1; }
echo -e "# Generated by gfwlist2privoxy at $(date '+%F %T')\n{+forward-override{forward-socks5 $1 .}}" >${gfwlist_action}

# convert gfwlist.txt
temporary_file=$(mktemp)
base64 -d       </dev/null &>/dev/null && base64='base64 -d'
base64 --decode </dev/null &>/dev/null && base64='base64 --decode'
[ "$base64" ] || { echo "[ERR] Command not found: 'base64'" 1>&2; exit 1; }
curl -4sSkL https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt | $base64 | perl -pe '
if (/URL Keywords/i) { $null = <> until $null =~ /^!/ }
s#^\s*+$|^!.*+$|^@@.*+$|^\[AutoProxy.*+$|^/.*/$##i;
s@^\|\|?|\|$@@;
s@^https?:/?/?@@i;
s@(?:/|%).*+$@@;
s@^\*\.@.@;
s@\.?\*$@.@;
s@(?=[^0-9a-zA-Z.*-]).*+$@@ unless /^\d+\.\d+\.\d+\.\d+(?::\d+)?$/;
s@^(?!\.|\s*+$|\d+\.\d+\.\d+\.\d+(?::\d+)?$)@.@;
s@^\.[^.]++$@@;
s@^\s*+$@@' >${temporary_file}
echo -e '.google.\n.blogspot.\n.twimg.edgesuite.net' >>${temporary_file}

# conversion completed
cat ${temporary_file} | perl -ne 'print if /^\d+\.\d+\.\d+\.\d+(?::\d+)?$/' | sort -n | uniq >>${gfwlist_action}
cat ${temporary_file} | perl -ne 'print unless /^\d+\.\d+\.\d+\.\d+(?::\d+)?$/' | sort | uniq >>${gfwlist_action}
rm -fr ${temporary_file}
cat << EOF
Generated file: '${gfwlist_action}'. Please put it in privoxy config directory.
Usually, the directory is '/etc/privoxy'. If yes, then exec following command:

mv -f ${gfwlist_action} /etc/privoxy
echo 'actionsfile ${gfwlist_action}' >>/etc/privoxy/config
service privoxy restart (via SysVinit)
systemctl restart privoxy.service (via Systemd)

Enjoy it!
EOF
